import { loginRequest } from '@/api/user'
import {
  getLonglivedToken,
  getToken,
  setLonglivedToken,
  setToken,
} from '@/utils/Auth.ts'

const getDefaultState = () => {
  return {
    token: getToken(),
    longlivedToken: getLonglivedToken(),
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  RESET_TOKEN: (state) => {
    state.token = ''
    state.longliveToken = ''
    setLonglivedToken('')
    setToken('')
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_LONG_LIVE_TOKEN: (state, token) => {
    state.longliveToken = token
    setLonglivedToken(token)
  },
}

const actions = {
  login({ commit }, userInfo): Promise<void> {
    console.log(userInfo)
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginRequest({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response
          console.log(response)
          commit('SET_TOKEN', data.token)
          commit('SET_LONG_LIVE_TOKEN', data.longlivedToken)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  logout({ commit }): Promise<void> {
    return new Promise((resolve) => {
      commit('RESET_TOKEN')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
